import React, { useEffect } from 'react';
import { Dialog, Field, Form, Input, Select } from '@alifd/next';
import { EntryMethodEnums, PropertyTypeEnums } from '@/pages/CommodityCenter/PropertyManage/entity';
import PropertyService from '../../service';
import { useRequest } from 'ice';

interface Props {
  visible: boolean;
  row: PropertyState.PropertyItem;
  onRefresh: () => void;
  onClose: () => void;
}

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};

const FormItem = Form.Item;

const CreateDialog: React.FC<Props> = (props) => {
  const field = Field.useField([]);
  const { visible, row, onRefresh = () => { }, onClose } = props;

  const { request, loading } = useRequest(PropertyService.createProperty, {
    manual: true,
    onSuccess: () => {
      onRefresh();
      onClose();
    },
  });

  useEffect(() => {
    if (visible) {
      field.setValues(row);
    } else {
      field.reset();
    }
  }, [visible]);

  const handleOk = () => {
    field.validate((errors, values): void => {
      if (errors) {
        return;
      }
      request({
        ...values,
        name: values.name.trim(),
        remark: values.remark?.trim(),
        id: row.id,
        enable: row.enable,
      });
    });
  };

  return (
    <Dialog
      shouldUpdatePosition
      overflowScroll
      visible={visible}
      onClose={onClose}
      title={`${row.id ? '编辑' : '新增'}属性`}
      style={{ width: 520 }}
      onOk={handleOk}
      okProps={{ loading }}
      onCancel={onClose}
    >
      <Form
        fullWidth
        labelAlign="left"
        field={field}
        useLabelForErrorMessage
        {...formItemLayout}
      >
        <FormItem
          label="属性名称:"
          name="name"
          required
        >
          <Input placeholder="请输入" maxLength={10} />
        </FormItem>
        <FormItem
          label="属性类型:"
          name="attrType"
          required
        >
          <Select dataSource={PropertyTypeEnums} />
        </FormItem>
        <FormItem
          label="录入方式:"
          required
          name="modeType"
        >
          <Select dataSource={EntryMethodEnums} />
        </FormItem>
        <FormItem
          label="属性值:"
          name="attrValues"
          required={field.getValue('modeType') !== 2}
          // hidden={field.getValue('modeType') === 2}
        >
          <Input.TextArea
            placeholder="多个属性之间以英文逗号分隔"
          />
        </FormItem>
        <FormItem
          label="属性描述:"
          name="remark"
        >
          <Input.TextArea placeholder="请输入" max={100} showLimitHint />
        </FormItem>
      </Form>
    </Dialog>
  );
};

export default CreateDialog;
